import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { Mt } from '@/api/manager/mt'
type StateStore = {
	actualSearchVal: string
	_start: string
	_changes: string[]
	poll_select_mt_key_list: string[]
	pollMembers: Mt[]
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	toggleClick: (mtKey: string) => void
	toggleCtrl: (mtKey: string) => void
	toggleShift: (mtKey: string) => void
}
const initialState: StateStore = {
	actualSearchVal: '',
	_start: '',
	_changes: [],
	poll_select_mt_key_list: [],
	pollMembers: [],
}
export const useBatchMemberListStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		toggleClick: (mtKey) => {
			const list = []
			list.push(mtKey)
			set({ poll_select_mt_key_list: [...list], _start: mtKey, _changes: [] })
		},
		toggleCtrl: (mtKey) => {
			const list = get().poll_select_mt_key_list
			let index = list.indexOf(mtKey)
			if (index === -1) {
				list.push(mtKey)
			} else {
				list.splice(index, 1)
			}
			set({ poll_select_mt_key_list: [...list], _start: mtKey, _changes: [] })
		},
		toggleShift: (mtKey) => {
			const { poll_select_mt_key_list: list, _changes, _start, pollMembers } = get()
			if (_changes.length > 0) {
				for (const item of pollMembers) {
					if (_changes.includes(item.mtKey)) {
						let index = list.indexOf(mtKey)
						list.splice(index, 1)
					}
				}
			}
			let result = []
			let newChanges = []
			let startItem = pollMembers.find((x) => x.mtKey === _start)
			console.log(list, startItem)
			if (startItem) {
				if (startItem?.mtKey === mtKey) {
					result.push(startItem?.mtKey)
					newChanges.push(startItem?.mtKey)
				} else {
					let _flag = false,
						_time = 0
					for (const item of pollMembers) {
						if (item.mtKey === mtKey || item.mtKey === _start) {
							result.push(item.mtKey)
							newChanges.push(item.mtKey)
							_flag = ++_time === 1
						}
						if (_flag) {
							result.push(item.mtKey)
							newChanges.push(item.mtKey)
						}
					}
				}
			}
			set({
				poll_select_mt_key_list: Array.from(new Set([...list, ...result])),
				_changes: Array.from(new Set([...newChanges])),
			})
		},
	}))
)
